package com.dlwx.firefighting;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.dlwx.firefighting.config.Constant;
import com.dlwx.firefighting.utils.LogUtils;
import com.dlwx.firefighting.utils.SPUtils;
import com.dlwx.firefighting.utils.ToastUtils;
import com.dlwx.firefighting.widget.MyImageLoader;
import com.fm.openinstall.OpenInstall;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.view.CropImageView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tencent.bugly.Bugly;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.tauth.Tencent;

import java.util.Date;

import cn.jpush.android.api.JPushInterface;


/**
 * Created by Administrator on 2017/7/4.
 */

public class MyApplication extends Application {
    private static Context aContext;
    private int foregroundActivityCount = 0;
    public static String HeadPic= Constant.Logo;
    public static Tencent mTencent;

    @Override
    public void onCreate() {
        super.onCreate();
        mTencent = Tencent.createInstance(Constant.QQ_APPID,this);
        // 全局context
        aContext = getApplicationContext();
        initJpush();
        //-----------------logutil开关--------------------------
        LogUtils.Builder builder = new LogUtils.Builder(this);
        builder.setGlobalTag("ccc");
        builder.setLogSwitch(true);
        //-----------------logutil开关--------------------------

        //-------------------Litepal----------------------------
//        LitePal.initialize(this);
        //--------------------Litepal---------------------------

        //----------------imagePicker---------------------------
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new MyImageLoader());   //设置图片加载器
        imagePicker.setMultiMode(true);  //图片选择模式 默认多选
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
        imagePicker.setSelectLimit(7);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setSaveRectangle(true);  //true 按照矩形保存，false 按照裁剪框形状保存
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
//        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
//        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
        //----------------imagePicker---------------------------
//      okgo初始化
        OkGo.getInstance().init(this);
//        腾讯web初始化
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                Log.d("app", " onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
        QbSdk.initX5Environment(this,cb);
//        腾讯bugly初始化
        Bugly.init(getApplicationContext(), "fb4c2ecaf4", false);
        if(isMainProcess()) {
            OpenInstall.init(this);
        }
//        ZXingLibrary.initDisplayOpinion(this);
       registerActivity();
    }

    private int  getForeAcitivity(){
        return foregroundActivityCount;
    }
//    计算前台activity,切换后台，和锁屏都会重新计算，并且不会累加。
       long start;
       long end;
    private void registerActivity() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(Activity activity) {
                if (foregroundActivityCount == 0) {
                    Log.i("CCC", "switch to foreground");
                    Date startDate = new Date(System.currentTimeMillis());
                    start = startDate.getTime();
                }
                foregroundActivityCount += 1;
            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {
                Log.i("CCC", "********");
                foregroundActivityCount -= 1;
                if(foregroundActivityCount == 0){
                    Log.i("CCC", "switch to background");
                }
                Date endDate = new Date(System.currentTimeMillis());
                end=endDate.getTime();
                long range=end-start;
                boolean isCountTime= (boolean) SPUtils.get(getApplicationContext(),Constant.IS_COUNT_TIME,true);
                Log.i("CCC", "********"+isCountTime+"-r:"+range);
                if(!isCountTime){
                    return;
                }
                if(range>(6*10*60*1000)){
                    giveMoney(60);
                    return;
                }else if(range>(5*10*60*1000)){
                    giveMoney(50);
                    return;
                }else if(range>(4*10*60*1000)){
                    giveMoney(40);
                    return;
                }else if(range>(3*10*60*1000)){
                    giveMoney(30);
                    return;
                }else if(range>(2*10*60*1000)){
                    giveMoney(20);
                    return;
                }else if(range>(1*10*60*1000)){
                    giveMoney(10);
                    return;
                }
            }
            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }
            @Override
            public void onActivityDestroyed(Activity activity) {
            }
        });
    }
//根据在线时长赠送余额
    private void giveMoney(final int type) {
        String userId= (String) SPUtils.get(getApplicationContext(),Constant.USER_ID,"");
        OkGo.<String>post(Constant.ONLINE)
                .params("user_id", userId)
                .params("online_time", type)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if(type==60){
                            SPUtils.put(getApplicationContext(), Constant.IS_COUNT_TIME,false);
                        }
//                        SPUtils.put(getApplicationContext(), Constant.IS_COUNT_TIME,false);
                    }
                    @Override
                    public void onError(Response<String> response) {
                        ToastUtils.toastForShort(getApplicationContext(), getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    public static Context getContext() {
        return aContext;
    }

    public boolean isMainProcess() {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) getSystemService
                (Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return getApplicationInfo().packageName.equals(appProcess.processName);
            }
        }
        return false;
    }

    /**
     * 初始化极光
     */
    private void initJpush() {
        JPushInterface.setDebugMode(true);    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);            // 初始化 JPush
    }


    @Override
    public void attachBaseContext(Context base) {
        MultiDex.install(base);
        super.attachBaseContext(base);
    }

    //-----------------------end--------------------------------
}
